package com.tsinghuabigdata.edu.ddmath.module.ddwork;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tsinghuabigdata.edu.ddmath.MVPModel.MyStudyModel;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.RoboForToolBarActivity;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.adapter.DDWorkPageAdapter;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.adapter.DDWorkQuestionAdapter;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.DDWorkDetail;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalPageInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalQuestionInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.WorkPageInfo;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.view.LoadingView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

/**
 * 豆豆作业列表界面
 */
public class DDWorkListActivity extends RoboForToolBarActivity implements DDWorkQuestionAdapter.CorrectUpdateListener, AdapterView.OnItemClickListener {

    public static final String PARAM_DDWORKID = "ddworkid";
    public static final String PARAM_TITLE    = "title";

    @ViewInject(R.id.loadingView)
    private LoadingView mLoadingView;

    //页List
    @ViewInject(R.id.ddwork_list_worklist)
    private ListView pageListView;

    //作业状态
    @ViewInject( R.id.ddwork_list_workstatuslayout )
    private RelativeLayout workStatusLayout;
    @ViewInject(R.id.ddwork_list_workstatus)
    private TextView workStatusView;

    @ViewInject( R.id.ddwork_list_qustionlist )
    private ListView questionListView;

    //已批阅
    @ViewInject(R.id.ddwork_list_correctlayout)
    private RelativeLayout correctedLayout;
    @ViewInject(R.id.ddwork_list_teachercorrect)
    private TextView teacherView;
    @ViewInject(R.id.ddwork_list_correctedResult)
    private TextView resultView;

    private Context mContext;
    //
    private DDWorkPageAdapter mPageAdapter;
    private DDWorkQuestionAdapter mQuestionAdapter;

    private MyStudyModel myStudyModel;

    //
    private String ddworkId;
    private String title;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_ddwork_list;
    }

    @Override
    protected void onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        //setTitle("待上传图册");
        setLeftTitle( "返回", R.color.white );
        setBarTextcolor(R.color.white);
        setUserBarBackgroud(true);

        x.view().inject( this );
        mContext = this;

        if( !parseIntent() ){
            ToastUtils.show( mContext, "参数错误", Toast.LENGTH_SHORT );
            finish();
            return;
        }
        initView();
        loadData();

    }

    @Override
    public void onLeftClick(){
        finish();
    }


    @Override
    public void updateImage(final ImageView answerImage, final Bitmap dstBitmap) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                answerImage.setImageBitmap( dstBitmap );
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //选中状态改变
        LocalPageInfo pageInfo = mPageAdapter.getItem( position );
        mPageAdapter.selectItem( position );

        //题目内容改变
        mQuestionAdapter.clear();
        mQuestionAdapter.addQuestionList( pageInfo.getQuestions(), position+1 );
        mQuestionAdapter.notifyDataSetChanged();
    }
    //----------------------------------------------------------------------
    private boolean parseIntent(){
        Intent intent = getIntent();
        ddworkId = intent.getStringExtra( PARAM_DDWORKID );
        title    = intent.getStringExtra( PARAM_TITLE );

        return !( TextUtils.isEmpty( ddworkId ) || TextUtils.isEmpty(title) );
    }
    private void initView(){

        //标题
        setTitle( title, R.color.white );

        mPageAdapter = new DDWorkPageAdapter( mContext, DDWorkDetail.WORK_SUBMITED );
        pageListView.setAdapter( mPageAdapter );
        pageListView.setOnItemClickListener( this );

        mQuestionAdapter = new DDWorkQuestionAdapter( mContext );
        mQuestionAdapter.setUpdateListener( this );
        questionListView.setAdapter( mQuestionAdapter );

        mLoadingView.setListener(new View.OnClickListener() {           //失败点击重新加载
            @Override
            public void onClick(View v) {
                loadData();
            }
        });

        myStudyModel = new MyStudyModel();
    }

    //加载的是本地保存的数据
    private void loadData(){


        LoginInfo loginInfo = AccountUtils.getLoginUser();
        UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
        if( loginInfo == null || detailinfo == null /*|| detailinfo.getJoinedClassInfoList()==null || detailinfo.getJoinedClassInfoList().size()==0*/ ){
            ToastUtils.show( mContext, "请登录", Toast.LENGTH_SHORT );
            return;
        }

        String accessToken = loginInfo.getAccessToken();
        String studentId   = detailinfo.getStudentId();
        //String classId     = detailinfo.getJoinedClassInfoList().get(0).getClassId();


//        DDWorkDetail workDetail = new DDWorkDetail();
//        workDetail.setPageCount( 2 );
//        workDetail.setExerStatus( 1 );
//        workDetail.setRightQuestionCount( 10 );
//        workDetail.setWrongQuestionCount( 5 );
//        workDetail.setLastReviewer( "张三" );
//
//        ArrayList<LocalPageInfo> pageList = new ArrayList<>();
//        workDetail.setPageInfo( pageList );
//
//        LocalPageInfo localPageInfo = new LocalPageInfo( ddworkId );
//        localPageInfo.setPageNum( 1 );
//        localPageInfo.setSelected( true );
//
//        ArrayList<LocalQuestionInfo> questionInfos = new ArrayList<>();
//        localPageInfo.setQuestions( questionInfos );
//
//        LocalQuestionInfo questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "stdjkfdjjdsksdfjfkjdsf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_CHOICE );
//        questionInfo.setIndexInPaper( 1 );
//        questionInfo.setStem( "1. 下列3条线段能构成三角形的是：" );
//        questionInfo.setSubStem( "     A.1,2,3\n    B.20,20,30\n    C.30,10,15\n    D.4,15,7" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.1, \"width\":1.0, \"height\":0.2}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "wewewewexcfvdsgfdgfdgfgf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_FILL_IN );
//        questionInfo.setIndexInPaper( 2 );
//        questionInfo.setStem( "1. 一列火车每小时行78.5千米，x小时行（            ）千米。" );
//        questionInfo.setQuestionArea("[{\"x\":0.5, \"y\":0.3, \"width\":0.8, \"height\":0.4}]");
//        questionInfos.add( questionInfo );
//
//        workDetail.getPageInfo().add( localPageInfo );
//
//        //-------------------------------------------
//        //第二页
//
//        localPageInfo = new LocalPageInfo( ddworkId );
//        localPageInfo.setPageNum( 2 );
//
//        questionInfos = new ArrayList<>();
//        localPageInfo.setQuestions( questionInfos );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "stdjkfdjjdsksdfjfkjdsf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_CHOICE );
//        questionInfo.setIndexInPaper( 1 );
//        questionInfo.setStem( "2. 22222 下列3条线段能构成三角形的是：" );
//        questionInfo.setSubStem( "     A.1,2,3\n    B.20,20,30\n    C.30,10,15\n    D.4,15,7" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.1, \"width\":1.0, \"height\":0.2}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "wewewewexcfvdsgfdgfdgfgf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_FILL_IN );
//        questionInfo.setIndexInPaper( 2 );
//        questionInfo.setStem( "3. 2222 一列火车每小时行78.5千米，x小时行（            ）千米。" );
//        questionInfo.setQuestionArea("[{\"x\":0.5, \"y\":0.3, \"width\":0.8, \"height\":0.4}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "sssssdfgdbhghjjhjkj" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_SOLUTION );
//        questionInfo.setIndexInPaper( 3 );
//        questionInfo.setStem( "1. 某校进行野外军训，甲、乙两队同时从学校出发。两队白天的行走速度是不同的，甲队每个白天行20千米，乙队行15千米，夜里两队的行走速度是相同的，结果甲队恰好用5个昼夜达目" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.6, \"width\":0.95, \"height\":0.9}]");
//        questionInfos.add( questionInfo );
//
//        workDetail.getPageInfo().add( localPageInfo );

        mLoadingView.showLoading();
        myStudyModel.queryDDWorkDetail(accessToken, studentId, ddworkId, new RequestListener() {
            @Override
            public void onSuccess(Object res) {

                DDWorkDetail workDetail = (DDWorkDetail)res;

                ArrayList<LocalPageInfo> list = workDetail.getPageInfo();
                //首页加载 错误 或者没有数据   显示无
                if( list == null || list.size() == 0 ){
                    mLoadingView.showFaultView( true );
                    return;
                }

                mLoadingView.hideall();

                //对题型进行分析，
                int index = 0;
                for(WorkPageInfo pageInfo : workDetail.getPageInfo() ){
                    index++;
                    for(LocalQuestionInfo questionInfo1 : pageInfo.getQuestions() ){
                        mQuestionAdapter.addQuestionType( questionInfo1.getQuestionType(), index );
                    }
                }

                //Collections.sort( list, new WorkComparable() );

                mQuestionAdapter.clear();
                mQuestionAdapter.addQuestionList( list.get(0).getQuestions(), 1 );
                mQuestionAdapter.notifyDataSetChanged();

                //如果是下拉加载，清除原列表数据
                mPageAdapter.clear();
                mPageAdapter.addAll( list );
                mPageAdapter.notifyDataSetChanged();

                if( workDetail.getExerStatus() == 0 ){      //待批阅
                    workStatusView.setVisibility( View.VISIBLE );
                    correctedLayout.setVisibility( View.GONE );

                    workStatusView.setText("待批阅");
                    workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_FFB555 ) );

                }else{
                    workStatusView.setVisibility( View.GONE );
                    correctedLayout.setVisibility( View.VISIBLE );

                    String data = workDetail.getLastReviewer()+"老师已批阅";
                    teacherView.setText( data );
                    data = "正确"+workDetail.getRightQuestionCount()+"题,  错误"+workDetail.getWrongQuestionCount()+"题";
                    resultView.setText( data );
                }

                //默认加载第一个
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                mLoadingView.showFaultView( false );
            }
        });
    }

}
